package cn.yao.quaggajsdemo

import android.Manifest
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.webkit.PermissionRequest
import android.webkit.WebChromeClient
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val pers = arrayOf(Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(pers, 201)
        } else {
            start()
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == 201){
            var count = 0
            for (i in grantResults){
                if(i == PackageManager.PERMISSION_GRANTED)count++
            }
            if(count == grantResults.count())
                start()
        }
    }

    fun start() {
        h5activity.settings.apply {
            this.javaScriptEnabled = true
        }
        h5activity.webChromeClient = object : WebChromeClient(){
            @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
            override fun onPermissionRequest(request: PermissionRequest?) {
                request?.let {
                    runOnUiThread {
                        it.grant(it.resources)
                    }
                }
            }
        }
        h5activity.loadUrl("file:///android_asset/html/index.html")
//        h5activity.loadUrl("file:///android_asset/html/camera_example.html")
//        h5activity.loadUrl("https://webrtc.github.io/samples/src/content/getusermedia/canvas/")
//        h5activity.loadUrl("https://webrtc.github.io/samples/src/content/getusermedia/gum/")
    }
}
